package com.hadluo.qq.server.mapper;

import com.hadluo.qq.server.entity.Group;
import org.apache.ibatis.annotations.*;
import java.util.List;
import java.util.Optional;

/**
 * 群组Mapper接口
 */
@Mapper
public interface GroupMapper {

    @Insert("INSERT INTO `groups` (group_number, group_name, description, owner_id, create_time, last_message, last_message_time) " +
            "VALUES (#{groupNumber}, #{groupName}, #{description}, #{ownerId}, #{createTime}, #{lastMessage}, #{lastMessageTime})")
    @Options(useGeneratedKeys = true, keyProperty = "id")
    void save(Group group);

    @Select("SELECT * FROM `groups` g INNER JOIN group_members m ON g.id = m.group_id WHERE m.user_id = #{userId}")
    List<Group> findGroupsByUserId(Long userId);

    @Select("SELECT * FROM `groups` WHERE id = #{groupId}")
    Optional<Group> findById(Long groupId);

    @Select("SELECT * FROM `groups` WHERE group_number = #{groupNumber}")
    Optional<Group> findByGroupNumber(String groupNumber);

    @Select("SELECT COUNT(*) > 0 FROM `groups` WHERE group_number = #{groupNumber}")
    boolean existsByGroupNumber(String groupNumber);

    @Select("SELECT * FROM `groups` WHERE group_name LIKE CONCAT('%', #{keyword}, '%') OR description LIKE CONCAT('%', #{keyword}, '%')")
    List<Group> searchGroups(String keyword);

    @Update("UPDATE `groups` SET group_name = #{groupName}, description = #{description}, last_message = #{lastMessage}, " +
            "last_message_time = #{lastMessageTime} WHERE id = #{id}")
    void update(Group group);

    @Delete("DELETE FROM `groups` WHERE id = #{groupId}")
    void delete(Long groupId);
}